//
//  WBRefreshControl.swift
//  sinaweiboFirst
//
//  Created by mac on 16/3/15.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit

private let RefreshHeight: CGFloat = 60

//定义枚举项 
enum WBRefreshStatus: Int {

    case Normal = 0   // 默认状态
    case Pulling = 1   //下拉临界值 等待刷新状态
    case Refreshing = 2 //正在刷新状态
}

class WBRefreshControl: UIControl {

// set 方法可以拿到 newValue  didSet方法可以拿到oldValue
    
    var states: WBRefreshStatus = .Normal {
        //属性设置监察器
        didSet {
            //匹配枚举项 
            switch states {
            case .Normal:
                print("下拉刷新")
                tipLabel.text = "下拉刷新"
                indicationView.stopAnimating()
                arrowIcon.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    //箭头原始状态
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    
                    if oldValue == .Refreshing {
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshHeight
                        self.scrollView?.contentInset = inset
                    }
                })
                
            case .Pulling:
                print("松手刷新 ")
                tipLabel.text = "松手刷新"
                //旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在刷新"
                arrowIcon.hidden = true
                indicationView.startAnimating()
                
                //做网络请求 刷新数据 
                self.sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += RefreshHeight
                    self.scrollView?.contentInset = inset
                })
            }
        }
    }
    
    func endRefreshing() {
    
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.states = .Normal
        }
    }

    
    //重写构造方法
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -RefreshHeight, width: ScreenW, height: RefreshHeight)
        super.init(frame: rect)
        
        self.backgroundColor = UIColor.blueColor()
        
        setupUI()
       
    }
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //实现KVO观察的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
       
//        print("------------------")
//        print(scrollView?.contentOffset)
//        print(scrollView?.contentInset)
//        print(scrollView?.contentSize)
//        print("------------------")
//        print(change)
        
        // 垂直方向的位移 临界值比较 修改三种状态
        //1.位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        //2.临界值 －124
        let condationValue = -(RefreshHeight + (scrollView?.contentInset.top ?? 0))
        if scrollView!.dragging {
        
            // 把状态判断放在前面效果好 临界值－124
            if states == .Pulling && offsetY > condationValue {
            
                //下拉刷新的普通提示状态
                states = .Normal
                
            } else if states == .Normal && offsetY < condationValue {
            
                //垂直方向位置 达到临界值 等待用户松手刷新状态
                states = .Pulling
            }
            
        } else {
            
            //用户松手状态 并且是等待刷新状态 -> 刷新状态
                if states == .Pulling {
                
                    states = .Refreshing
            }
        }
    }
    

    //将要添加到新的父视图
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断newSuperview是不是scrollView或其子视图
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
        
//需要判断下拉刷新控件的父视图是否是UIScrollView及子类 可以提供ScrollView TableView CollectionView 来进行下拉刷新使用  将父视图记录下来
            scrollView = myFather
            
            //观察父视图的contentOffset 这个属性的变化
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    
    private func setupUI() {
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        
        //设置约束
        
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }

    private var scrollView: UIScrollView?
    
    private lazy var tipLabel: UILabel = UIFactory.labelFactory("下拉刷新", textColor: UIColor.darkGrayColor(), fontSize: 14)
    
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
    /* 移除监听 */
    deinit {
    
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
